package com.sc.nft.admin.controller;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.XmlUtil;
import com.sc.nft.admin.request.NotifyRequest;
import com.sc.nft.admin.service.QywxService;
import com.sc.nft.admin.util.qywx.AesException;
import com.sc.nft.admin.util.qywx.WXBizJsonMsgCrypt;
import com.sc.nft.wrapper.RequestWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;


@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/admin/qywx")
@Api(tags = "企业微信后台控制器")
@ApiIgnore
public class QyWxAdminController {

    public final WXBizJsonMsgCrypt crypt;
    public final QywxService qywxService;

    @ApiOperation(value = "地址验签", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_VALUE)
    @GetMapping(value = "/back", produces = MediaType.APPLICATION_JSON_VALUE)
    public String check(String msg_signature, String timestamp, String nonce, String echostr) throws AesException {
        String s = crypt.VerifyURL(msg_signature, timestamp, nonce, echostr);
        log.info("消息验证结果,{}", s);
        return s;
    }

    @ApiOperation(value = "消息通知", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping(value = "/back", produces = MediaType.APPLICATION_JSON_VALUE)
    public String notify(NotifyRequest request, HttpServletRequest servletRequest) throws AesException {
        String s = null;
        String body = new RequestWrapper(servletRequest).getBody();
        log.info("body{}", body);
        Map<String, Object> map = XmlUtil.xmlToMap(body);
        String Encrypt = MapUtil.getStr(map, "Encrypt");
        log.info("Encrypt:{}", Encrypt);
        s = qywxService.handleMsg(request.getMsg_signature(), request.getTimestamp(), request.getNonce(), Encrypt);
        return s;
    }

}
